<template>
  <div>
    <!-- 操作按钮移动到顶部 -->
    <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 10px;">
      <el-button type="primary" @click="dialogVisible = true">添加图书类型</el-button>
      <el-button type="danger" @click="handleDelete" :disabled="!selectedRows.length">批量删除</el-button>
      <el-button @click="handleEdit(selectedRows[0])" :disabled="selectedRows.length !== 1">编辑选中项</el-button>
    </div>

    <!-- 表格展示 -->
    <el-table
        :data="bookTypes"
        style="width: 100%"
        :height="700"
        @selection-change="handleSelectionChange"
        :row-class-name="getRowClass"
        ref="bookTable"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="typeId" label="ID" width="100"></el-table-column>
      <el-table-column prop="typeName" label="名称" width="200"></el-table-column>
      <el-table-column prop="typeContent" label="描述" width="400">
        <template #default="scope">
          <div @click="showContentDialog(scope.row.typeContent)">
            <el-tooltip effect="dark" :content="scope.row.typeContent" placement="top">
              <span class="description-text">{{ truncateText(scope.row.typeContent, 50) }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog title="添加/编辑图书类型" v-model="dialogVisible" width="30%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.typeName"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea"  :autosize="{ minRows: 2, maxRows: 10 }" v-model="form.typeContent"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 描述查看弹窗 -->
    <el-dialog title="描述详情" v-model="contentDialogVisible" width="40%">
      <p>{{ contentDialogText }}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="contentDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import http from '../utils/axios';

const bookTypes = ref([]);
const dialogVisible = ref(false);
const contentDialogVisible = ref(false);
const contentDialogText = ref('');
const selectedRows = ref([]);
const form = ref({
  typeId: null,
  typeName: '',
  typeContent: '',
});

const bookTable = ref(null);

// 格式化时间
const formatDate = (date) => {
  const d = new Date(date);
  return d.toLocaleString();
};

// 获取图书类型数据
const fetchBookTypes = () => {
  http.get('/Type/all').then(response => {
    if (response.status) {
      bookTypes.value = response.data;
    }
  }).catch(error => {
    ElMessage.error('获取图书类型失败');
    console.error(error);
  });
};

// 编辑图书类型
const handleEdit = (row) => {
  if (!row) return;
  form.value = {...row};
  dialogVisible.value = true;
};

// 删除图书类型
const handleDelete = () => {
  const ids = selectedRows.value.map(row => row.typeId);
  const deletePromises = ids.map(id => http.delete(`/Type/delete/${id}`));
  Promise.allSettled(deletePromises).then(results => {
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        ElMessage.success(`删除成功: ID ${ids[index]}`);
      } else {
        // 提取具体的错误信息
        const errorMessage = result.reason.response?.data?.data || '删除失败';
        ElMessage.error(`删除失败: ${errorMessage}`);
      }
    });
    fetchBookTypes();
  }).catch(error => {
    ElMessage.error('删除操作失败', error);
  });
};


// 提交表单
const handleSubmit = () => {
  if (form.value.typeId) {
    // 更新操作
    http.put(`/Type/update/${form.value.typeId}`, {
      typeName: form.value.typeName,
      typeContent: form.value.typeContent,
    }).then(() => {
      fetchBookTypes();
      ElMessage.success('更新成功');
    }).catch(error => {
      ElMessage.error('更新图书类型失败',error);
    });
  } else {
    // 添加操作
    http.post('/Type/save', form.value).then(() => {
      fetchBookTypes();
      ElMessage.success('添加成功');
    }).catch(error => {
      ElMessage.error('添加图书类型失败',error);
    });
  }
  dialogVisible.value = false;
};

// 描述弹窗
const showContentDialog = (content) => {
  contentDialogText.value = content;
  contentDialogVisible.value = true;
};

// 文本截断
const truncateText = (text, length) => {
  return text.length > length ? text.slice(0, length) + '...' : text;
};

// 选择变更
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 获取行样式
const getRowClass = ({row}) => {
  return selectedRows.value.includes(row) ? 'selected-row' : '';
};

onMounted(() => {
  fetchBookTypes();
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.description-text {
  cursor: pointer;
  text-decoration: underline;
  color: #409eff;
}

</style>
